package cloud.pangui.core.lock.autoconfig;

import cloud.pangui.core.lock.annotation.GlobalLock;
import cloud.pangui.core.lock.resolver.LockResolverFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.PriorityOrdered;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * bean加载时对分布式锁的注解进行预编译
 *
 * @Auther hepangui
 * @Date 2019/5/10 0010
 */
@Configuration
public class GlobalLockBeanPostProcessor implements BeanFactoryAware, BeanPostProcessor {

	private BeanFactory beanFactory;

	@Override
	public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {

		Class<?> beanType = bean.getClass();
		Method[] methods = beanType.getMethods();
		for (Method method : methods) {
			GlobalLock annotation = AnnotationUtils.findAnnotation(method, GlobalLock.class);
			if (annotation != null) {
				LockResolverFactory bean1 = beanFactory.getBean(LockResolverFactory.class);
				bean1.buildResolver(method, annotation);
			}
		}
		return bean;
	}

	@Override
	public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
		this.beanFactory = beanFactory;
	}
}